// pages/power/power.js
import api from "../../utils/apis.js";
import message from "../../utils/message.js"
import util from "../../utils/util.js"

Page({
  data: {
    pageSize: 20,
    pageNum: 0,
    powerListData: [],
    bottomTitle: '点击加载更多'
  },

  onLoad: function(options) {
    wx.startPullDownRefresh(this.data.pageNum)
  },

  onPullDownRefresh: function() {
    this.setData({
      pageNum: 0
    })

    this.gainPowerList(this.data.pageNum)
  },

  onReachBottom: function() {
    if (this.data.bottomTitle === '无更多数据') {
      return
    }

    this.loadMore()
  },

  loadMore() {
    let self = this

    if (self.data.bottomTitle === '无更多数据') {
      return
    }

    let temp = self.data.pageNum;
    temp += 1;
    self.setData({
      pageNum: temp
    });

    self.gainPowerList(self.data.pageNum)
  },

  gainPowerList(pageNum) {
    let self = this

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: '加载中',
    })

    wx.request({
      url: api.powerListApi + "?" + "page=" + pageNum + "&size=" + self.data.pageSize,
      method: "GET",
      header: {
        "Authorization": 'Bearer ' + token
      },
      success(res) {
        wx.hideLoading()
        wx.stopPullDownRefresh()

        if (res.statusCode == '200') {
          if (res.data.length == 0) {
            self.setData({
              bottomTitle: '无更多数据'
            });
            return
          }

          if (self.data.pageNum == 0) {
            self.setData({
              powerListData: []
            })
          }

          let temp = []
          self.data.powerListData.forEach(element => {
            temp.push(element)
          })
          
          res.data.forEach(element => {
            let time = element.endDate
            let space = time.indexOf(" ");
            let newString = time.slice(0, space);
            element.endDate = newString;
            temp.push(element)
          })

          self.setData({
            powerListData: temp
          })
        } else {
          util.errHandler(res)
        }
      }
    });
  }
})